#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
火电厂冷端优化系统 - 简单测试脚本
用于快速验证系统的基本功能
"""

import numpy as np
import sys
import os

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

def test_imports():
    """测试所有必要的模块导入"""
    print("测试模块导入...")
    
    try:
        from opt_alg.mechine import steam_turbine, Condenser, Heat_recovery_system
        print("✓ 设备模型模块导入成功")
    except Exception as e:
        print(f"✗ 设备模型模块导入失败: {e}")
        return False
    
    try:
        from opt_alg.param_ident2 import share_data
        print("✓ 参数辨识模块导入成功")
    except Exception as e:
        print(f"✗ 参数辨识模块导入失败: {e}")
        return False
    
    try:
        from opt_alg.bi_mp_pro2 import parallel_optimize
        print("✓ 优化算法模块导入成功")
    except Exception as e:
        print(f"✗ 优化算法模块导入失败: {e}")
        return False
    
    try:
        from pyXSteam.XSteam import XSteam
        print("✓ 蒸汽热力性质模块导入成功")
    except Exception as e:
        print(f"✗ 蒸汽热力性质模块导入失败: {e}")
        return False
    
    return True

def test_steam_properties():
    """测试蒸汽热力性质计算"""
    print("\n测试蒸汽热力性质计算...")
    
    try:
        from pyXSteam.XSteam import XSteam
        
        steam = XSteam(XSteam.UNIT_SYSTEM_MKS)
        
        # 测试基本热力性质计算
        P = 15.0  # MPa
        T = 540   # °C
        
        h = steam.h_pt(P*10, T)  # 焓值
        s = steam.s_pt(P*10, T)  # 熵值
        v = steam.v_pt(P*10, T)  # 比体积
        
        print(f"✓ 蒸汽热力性质计算成功:")
        print(f"  压力: {P} MPa, 温度: {T} °C")
        print(f"  焓值: {h:.2f} kJ/kg")
        print(f"  熵值: {s:.4f} kJ/(kg·K)")
        print(f"  比体积: {v:.6f} m³/kg")
        
        return True
    except Exception as e:
        print(f"✗ 蒸汽热力性质计算失败: {e}")
        return False

def test_turbine_model():
    """测试汽轮机模型"""
    print("\n测试汽轮机模型...")
    
    try:
        from opt_alg.mechine import steam_turbine
        
        # 创建汽轮机模型
        turbine = steam_turbine(ita=0.85)
        
        # 测试调节级计算
        Ts = 540    # 主汽温度 °C
        Pst = 15.0  # 主汽压力 MPa
        Dst = 400   # 主汽流量 t/h
        
        Dt, pt, ht, t, ne = turbine.regulating_level(Ts, Pst, Dst)
        
        print(f"✓ 汽轮机模型计算成功:")
        print(f"  调节级后流量: {Dt:.2f} t/h")
        print(f"  调节级后压力: {pt:.3f} MPa")
        print(f"  调节级后焓值: {ht:.2f} kJ/kg")
        print(f"  调节级后温度: {t:.2f} °C")
        print(f"  调节级功率: {ne:.2f} MW")
        
        return True
    except Exception as e:
        print(f"✗ 汽轮机模型计算失败: {e}")
        return False

def test_condenser_model():
    """测试凝汽器模型"""
    print("\n测试凝汽器模型...")
    
    try:
        from opt_alg.mechine import Condenser
        
        # 创建凝汽器模型
        condenser = Condenser()
        
        # 测试凝汽器计算
        Pc = 0.006  # 背压 MPa
        n = 56      # 风机台数
        n_num = 60  # 风机转速 rpm
        Dc = 320    # 凝结水流量 t/h
        Ta = 25     # 环境温度 °C
        
        deta_Pc, Pc_new, Dec, Tc, Hc1, Vf, NTU, Qc = condenser.simulation(
            Hc=2400, Dc=Dc, Pc=Pc, n=n_num, Ta=Ta, h=0.1, kc_est=1.0
        )
        
        print(f"✓ 凝汽器模型计算成功:")
        print(f"  背压变化: {deta_Pc:.6f} MPa")
        print(f"  新背压: {Pc_new:.6f} MPa")
        print(f"  凝结水流量: {Dec:.2f} t/h")
        print(f"  冷却水温度: {Tc:.2f} °C")
        
        return True
    except Exception as e:
        print(f"✗ 凝汽器模型计算失败: {e}")
        return False

def test_data_generation():
    """测试模拟数据生成"""
    print("\n测试模拟数据生成...")
    
    try:
        from simulation_runner import MockDataGenerator
        
        # 创建数据生成器
        generator = MockDataGenerator()
        
        # 生成单个数据点
        timestamp, data = generator.generate_single_data_point(base_load=400)
        
        print(f"✓ 模拟数据生成成功:")
        print(f"  数据维度: {data.shape}")
        print(f"  机组负荷: {data[1]:.2f} MW")
        print(f"  主汽流量: {data[2]:.2f} t/h")
        print(f"  主汽温度: {data[3]:.2f} °C")
        print(f"  背压: {data[15]:.3f} kPa")
        
        # 生成历史数据
        history_data = generator.generate_history_data(n_points=10, base_load=400)
        
        print(f"  历史数据维度: {history_data.shape}")
        
        return True
    except Exception as e:
        print(f"✗ 模拟数据生成失败: {e}")
        return False

def test_optimization_parameters():
    """测试优化参数获取"""
    print("\n测试优化参数获取...")
    
    try:
        from opt_alg.param_ident2 import share_data
        
        # 获取模型参数
        ita_current, kc_current, sim_steps = share_data()
        
        print(f"✓ 优化参数获取成功:")
        print(f"  汽轮机效率: {ita_current:.4f}")
        print(f"  凝汽器系数: {kc_current:.4f}")
        print(f"  仿真步数: {sim_steps}")
        
        return True
    except Exception as e:
        print(f"✗ 优化参数获取失败: {e}")
        return False

def main():
    """主测试函数"""
    print("=" * 60)
    print("火电厂冷端优化系统 - 功能测试")
    print("=" * 60)
    
    tests = [
        test_imports,
        test_steam_properties,
        test_turbine_model,
        test_condenser_model,
        test_data_generation,
        test_optimization_parameters
    ]
    
    passed = 0
    total = len(tests)
    
    for test in tests:
        try:
            if test():
                passed += 1
        except Exception as e:
            print(f"✗ 测试异常: {e}")
    
    print("\n" + "=" * 60)
    print(f"测试结果: {passed}/{total} 通过")
    
    if passed == total:
        print("✓ 所有测试通过！系统可以正常运行。")
        print("\n下一步可以运行:")
        print("  python simulation_runner.py test    # 快速测试")
        print("  python simulation_runner.py         # 完整仿真")
    else:
        print("✗ 部分测试失败，请检查依赖安装。")
        print("\n请确保安装了所有依赖:")
        print("  pip install -r requirements.txt")
    
    print("=" * 60)

if __name__ == "__main__":
    main() 